package com.lsf.dunlian.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.lsf.dunlian.Myappliction;
import com.lsf.dunlian.R;
import com.lsf.dunlian.adapter.GroupChatRecycleViewAdapter;
import com.lsf.dunlian.callback.GroupChatCallBack;
import com.lsf.dunlian.config.NettyConfig;
import com.lsf.dunlian.config.PreferenceUtil;
import com.lsf.dunlian.config.Urls;
import com.lsf.dunlian.constant.Constant;
import com.lsf.dunlian.databinding.GroupchatActivityBinding;
import com.lsf.dunlian.entity.ChatRecordEntity;
import com.lsf.dunlian.entity.ChatRecordVo;
import com.lsf.dunlian.entity.GroupChatMessageVo;
import com.lsf.dunlian.entity.MessageEntity;
import com.lsf.dunlian.enums.MsgTypeEnum;
import com.lsf.dunlian.netty.SimpleClientHandler;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GroupChatActivity extends Activity implements GroupChatCallBack {
    private GroupchatActivityBinding binding;
    private GroupChatRecycleViewAdapter chatAdapter;
    private List<ChatRecordEntity> list = new ArrayList<>();
    private LayoutInflater inflater;
    private String receiveUserId;
    private String userId;
    private String receiveUserName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseUtils.setStatusBar(this);
        inflater = LayoutInflater.from(this);
        binding = DataBindingUtil.inflate(inflater, R.layout.groupchat_activity, null, false);
        Intent intent = getIntent();
        receiveUserId = intent.getStringExtra("receiveUserId");
        receiveUserName = intent.getStringExtra("receiveUserName");
        binding.title.setText(receiveUserName);
        setContentView(binding.getRoot());
        userId= PreferenceUtil.getSharedPreference(Constant.USERID);
        chatAdapter = new GroupChatRecycleViewAdapter(this, list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setStackFromEnd(true);
        binding.recyclerview.setLayoutManager(layoutManager);
        binding.recyclerview.setAdapter(chatAdapter);
        SimpleClientHandler.register(this);
        init();
        getData();
    }

    private void init() {
        binding.sendBtn.setOnClickListener(v -> {
            send(MsgTypeEnum.MESSAGE_TEXT.getName(), binding.content.getText().toString());
        });
        binding.img.setOnClickListener(v -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                if (ContextCompat.checkSelfPermission(GroupChatActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(GroupChatActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    Toast.makeText(GroupChatActivity.this, "请开启相机权限！", Toast.LENGTH_SHORT);
                    return;
                }
            }
            if (binding.menu.getVisibility() == View.VISIBLE) {
                binding.menu.setVisibility(View.GONE);
            } else {
                binding.menu.setVisibility(View.VISIBLE);
            }
        });
        binding.back.setOnClickListener(v -> finish());
        binding.content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isNotEmpty(s.toString())) {
                    binding.sendBtn.setVisibility(View.VISIBLE);
                } else {
                    binding.sendBtn.setVisibility(View.GONE);
                }
            }
        });
    }

    private void getData() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().get().url(Urls.USERCHATRECEOD+"?createUserId="+userId+"&receiveUserId="+receiveUserId).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) { }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    ChatRecordVo vo = new Gson().fromJson(result,ChatRecordVo.class);
                    if (vo==null || vo.data==null) return;
                    for (ChatRecordEntity recordEntity : vo.data) {
                        if (recordEntity.createUserId.equals(PreferenceUtil.getSharedPreference(Constant.USERID))) {
                            recordEntity.isFriendMsg= false;
                        } else {
                            recordEntity.isFriendMsg =true;
                        }
                    }
                    
                    list.addAll(vo.data);
                    runOnUiThread(() -> chatAdapter.notifyDataSetChanged());
                }
            }
        });
    }


    @Override
    public void message(GroupChatMessageVo vo) {
        if (!userId.equals(vo.getReceiveUserId())) return;
        ChatRecordEntity entity = new ChatRecordEntity();

        if (vo.getCreateUserId().equals(PreferenceUtil.getSharedPreference(Constant.USERID))) {
            vo.setFriendMsg(false);
        } else {
            vo.setFriendMsg(true);
        }
        entity.createUserId=vo.getCreateUserId();
        entity.createUserIcon=vo.getCreateUserIcon();
        entity.createUserName=vo.getCreateUserName();
        entity.receiveUserId=vo.getReceiveUserId();
        entity.receiveUserIcon=vo.getReceiveUserIcon();
        entity.msgContent=vo.getMsgContent();
        entity.msgType=vo.getMsgType();
        entity.messageId=vo.getMsgId();
        list.add(entity);
        updateMsgUi();
    }


    @Override
    protected void onResume() {
        super.onResume();
        Myappliction.netty();
    }


    private void updateMsgUi() {
        runOnUiThread(() -> {
            binding.recyclerview.smoothScrollToPosition(list.size());
            chatAdapter.notifyDataSetChanged();
        });
    }

    private void send(String type, String message) {
        String id = String.valueOf(System.currentTimeMillis());
        ChatRecordEntity vo = new ChatRecordEntity();
        vo.isFriendMsg=false;
        vo.messageId=id;
        vo.createUserIcon="https://lsfimg.oss-cn-zhangjiakou.aliyuncs.com/icon/1606887388727.png";
        vo.msgType=type;
        vo.receiveUserId =receiveUserId;
        vo.msgContent=message;
        list.add(vo);
        updateMsgUi();

        new Thread(() -> {
            MessageEntity entity = new MessageEntity();
            entity.createUserId = userId;
            entity.msgType = type;
            entity.msgContent = message;
            entity.messageId = id;
            entity.receiveUserId = receiveUserId;
            Myappliction.channel.writeAndFlush(JSONObject.toJSONString(entity) + NettyConfig.DATA_PACK_SEPARATOR);
        }).start();
        binding.content.setText(null);
    }

}
